package com.jixiantubu.wode.shezhi;



import java.io.File;


import android.content.Context;

import android.os.Environment;

public class FileUtils {

	private static final double KB = 1024.0;
	private static final double MB = KB * KB;
	private static final double GB = KB * KB * KB;


	 
	public static String getFileNameNoEx(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length()))) {
				return filename.substring(0, dot);
			}
		}
		return filename;
	}

	/**
	 * 格式化大小
	 * 
	 * @param size
	 * @return
	 */
	public static String formatSize(long size) {
		String fileSize;
		if (size < KB)
			fileSize = size + "B";
		else if (size < MB)
			fileSize = String.format("%.1f", size / KB) + " KB";
		else if (size < GB)
			fileSize = String.format("%.1f", size / MB) + " MB";
		else
			fileSize = String.format("%.1f", size / GB) + " GB";

		return fileSize;
	}
	public static  File getPicturesStorageDir(Context context, String albumName) {

		// 获得应用私有的图片目录
		File file = new File(context.getExternalFilesDir(
				Environment.DIRECTORY_PICTURES), albumName);
		if (!file.mkdirs()) {
			System.out.println("Directory not created");
		}
		return file;
	}
	public static boolean getSdAvailable() {
		return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
	}

	public static String getExternalCacheDir(Context context) {
		String path = null;
		if (getSdAvailable()) {
			File file = context.getExternalCacheDir();
			if (file != null) {
				path = file.getAbsolutePath();
			} else {
				path = context.getCacheDir().getAbsolutePath();
			}
		} else {
			path = context.getCacheDir().getAbsolutePath();
		}
		return path;
	}
	
	public static long getFileSize(File f) {
		if (f == null || !f.exists()) {
			return 0;
		}
		long size = 0;
		File flist[] = f.listFiles();
		for (File file : flist) {
			if (file.isDirectory()) {
				size = size + getFileSize(file);
			} else {
				size = size + file.length();
			}
		}
		return size;
	}
	public static boolean delete(File file) {
		if (file != null && file.isFile()) {
			file.delete();
			return false;
		}
		if (file.isDirectory()) {
			File[] childFile = file.listFiles();
			if (childFile == null || childFile.length == 0) {
				file.delete();
				return true;
			}
			for (File f : childFile) {
				delete(f);
			}
			file.delete();
		}
		return true;
	}
}
